<?php
/**
 * @Created on 2020/01/15
 * @Author QQ 1026269609@qq.com
*/
namespace app\admin\controller;
use think\Controller;
use think\Db;

class Role extends Base
{
    public function index(){
    	$info=db('auth_group')->where('status','1')->order('id desc')->select();
    	$this->assign('info',$info);
        return $this->fetch();
    }
    public function addrole(){
    	if(request()->isPost()){
			$title=request()->param('title');
			$data=['title'=>$title];
			$info=db('auth_group')->where('title',$title)->find();
			if($info){
				return json(['status'=>0,'message'=>'名称已存在']);
			}
			$true=db('auth_group')->insert($data);
			if($true){
				return json(['status'=>1,'message'=>'添加成功']);
			}else{
				return json(['status'=>0,'message'=>'添加失败']);
			}
    	}else{
			return $this->fetch();
    	}
    }
    public function editrole(){
    	if(request()->isPost()){
    		$id=request()->param('id');
			$title=request()->param('title');
			$data=['title'=>$title];
			$info=db('auth_group')->where('id','neq',$id)->where('title',$title)->find();
			if($info){
				return json(['status'=>0,'message'=>'名称已存在']);
			}
			$true=db('auth_group')->where('id',$id)->update($data);
			if($true){
				return json(['status'=>1,'message'=>'修改成功']);
			}else{
				return json(['status'=>0,'message'=>'修改失败']);
			}
    	}else{
    		$id=request()->param('id');
			$info=db('auth_group')->where('id',$id)->find();
			$this->assign('info',$info);
			return $this->fetch();
    	}
    }
    public function delrole(){
    	$id=request()->param('id');
		$info=db('member')->where('roleid',$id)->find();
		if($info){
			return json(['status'=>0,'message'=>'该角色下存在用户，无法删除']);
		}
		$true=db('auth_group')->where('id',$id)->delete();
		if($true){
			return json(['status'=>1,'message'=>'删除成功']);
		}else{
			return json(['status'=>0,'message'=>'删除失败']);
		}
    }
    public function setauth(){
    	if(request()->isPost()){
    		$id=request()->param('id');
			$rule=input('post.rules/a');//强制转换为数组类型
			$rules=implode(',',$rule);
			db('auth_group')->where(['id'=>$id])->update(['rules'=>$rules]);
			return $this->fetch('role/setauthok');
    	}else{
    		$id=request()->param('id');
			$this->assign('id',$id);
			$data=db('auth_rule')->where(['pid'=>0,'status'=>1])->order('sort ASC')->select();
			foreach($data as $k=>$v){//二级菜单
				$data[$k]['two']=db('auth_rule')->where(['pid'=>$v['id'],'status'=>1])->order('sort ASC')->select();
				foreach($data[$k]['two'] as $kk=>$vv){//其它菜单
					$data[$k]['two'][$kk]['ree']=db('auth_rule')->where(['pid'=>$vv['id'],'status'=>1])->order('sort ASC')->select();
				}
			}
			$this->assign('data',$data);
			$rules=db('auth_group')->where(['id'=>$id])->find();
			$this->assign('rules',$rules);
    		return $this->fetch();
    	}
    } 
}